package tag

import (
	"encoding/json"
	"fmt"
	"myblogs/Lib/redis"
	"myblogs/app/variable"
	"time"
)

type TagModel struct {
	Id          int64
	Name        string
	AliasName   string `db:"alias_name"`
	Description string
	Status      int8
	Total       int64
	Cover       string
}

func (t *TagModel) GetTagAll(limit int64) []*TagModel {
	var tags []*TagModel
	result, err := redis.RedisClient().Get("Article:Tags").Result()
	if err != nil {
		fmt.Printf("%s\n", err)
	} else {
		if result != "" {
			err := json.Unmarshal([]byte(result), &tags)
			if err != nil {
				fmt.Printf("error: %s\n", err)
			} else {
				return tags
			}
		}
	}

	where := ""
	if limit > 0 {
		where = " LIMIT " + fmt.Sprintf("%d", limit)
	}

	strSql := "SELECT * FROM tags WHERE status=1 " + where
	err = variable.Db.Select(&tags, strSql)
	if err != nil {
		return nil
	}

	jsonData, _ := json.Marshal(tags)
	_, err = redis.RedisClient().Set("Article:Tags", jsonData, time.Hour*24).Result()
	if err != nil {
		fmt.Printf("error:%s\n", err)
	}

	return tags
}

func (t *TagModel) GetTagTotal() int64 {
	strSql := "SELECT COUNT(*) FROM tags WHERE status=1"
	var total int64
	err := variable.Db.Get(&total, strSql)
	if err != nil {
		return 0
	}
	return total
}

func (t *TagModel) GetTagArticleTotal() []map[string]int64 {
	var tagArticleTotal []struct {
		TagId int64 `db:"tag_id"`
		Total int64
	}

	strSql := "SELECT tag_id, COUNT(*) AS total FROM article_tag_relation GROUP BY tag_id"
	err := variable.Db.Select(&tagArticleTotal, strSql)
	if err != nil {
		return nil
	}

	var articleTagMap []map[string]int64
	for _, item := range tagArticleTotal {
		mp := map[string]int64{
			"tagId": item.TagId,
			"total": item.Total,
		}
		articleTagMap = append(articleTagMap, mp)
	}

	return articleTagMap
}
